package cn.terminus.web.customer.common;

import cn.terminus.result.common.context.TerminusCallContext;
import cn.terminus.result.common.context.builder.TerminusCallContextBuilder;
import cn.terminus.result.common.context.holder.TerminusSessionContextHolder;
import cn.terminus.result.common.serial.UUIDSerial;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * ClassName: AbstractTerminusController <br/>
 * Function: 控制器父类类. <br/>
 *
 * @author ty
 * @version 1.0.0
 * @since JDK 1.8
 */
public abstract class AbstractTerminusController {

    protected final Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 消息源资源
     */
    @Autowired
    private MessageSource messageSource;
    /**
     * Id生成
     */
    @Autowired
    private UUIDSerial uuidSerial;

    /**
     * session 持有者
     */
    @Autowired
    private TerminusSessionContextHolder terminusSessionContextHolder;

    /**
     * 创建上下文
     *
     * @return 请求上下文
     */
    public TerminusCallContext getTerminusContext() {
        return TerminusCallContextBuilder.buildContext(terminusSessionContextHolder);
    }

    /**
     * 获取HTTP Servlet Request
     *
     * @return Request
     */
    public HttpServletRequest getHttpServletRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    /**
     * 消息翻译
     *
     * @param code
     * @param defaultMsg
     * @return
     */
    public String getMessage(String code, String defaultMsg) {
        return this.messageSource.getMessage(code, null, defaultMsg, LocaleContextHolder.getLocale());
    }

    /**
     * 获取对应编码的信息描述
     *
     * @param code 编码
     * @return 消息message
     */
    public String getMessage(String code) {
        return this.getMessage(code, "");
    }

    /**
     * 获取全局ID
     *
     * @return
     */
    public String uuid() {
        return uuidSerial.uuid();
    }
}
